package com.st.sprinbootevent;

import com.st.sprinbootevent.event.CustomEvent;
import com.st.sprinbootevent.entity.User;
import com.st.sprinbootevent.event.UserEvent;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;

@Service("eventUserService")
public class UserService implements ApplicationContextAware, ApplicationEventPublisherAware {
 
    private ApplicationContext applicationContext;
    private ApplicationEventPublisher applicationEventPublisher;
 
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
 
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
 
    public String addUser(User user) {
        // 保存用户
        user.setId(1L);
        user.setName("name-1");
        // 发生事件（发邮件、发短信、、、）
        applicationContext.publishEvent(new UserEvent(user.toString()));
        // 两种发生方式一致
        //applicationEventPublisher.publishEvent(new UserEvent(user.toString()));
        return "ok";
    }

    /**
     *  触发事件
     * @param user
     */
    public void addTest(User user) {
        user.setId(1L);
        user.setName("name-1");
        // 发生事件
        applicationContext.publishEvent(new CustomEvent(user.toString(), "test"));
    }
}